﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

using Photon.SocketServer;
using Common;
using Common.Tools;
using Common.Model;

using MyGameServer.Manager;
using MyGameServer.Model;
using System.IO;
using System.Xml.Serialization;

namespace MyGameServer.Handler
{
    class JoinRoomHandler : BaseHandler
    {
        public JoinRoomHandler()
        {
            OpCode = OperationCode.JoinRoom;
        }
        public override void OnOperationRequest(OperationRequest operationRequest, SendParameters sendParameters, ClientPeer peer)
        {
            int roomId = (int)DictTool.GetValue<byte, object>(operationRequest.Parameters, (byte)ParameterCode.JoinRoom);
            Room room = Functions.GetRoom(MyGameServer.Instance.roomList, roomId); // 进入的房间
            CommonUser user = new CommonUser(); // 玩家自己
            user.id = peer.uuid; // 玩家id
            user.username = peer.username; // 玩家姓名
            


            OperationResponse response = new OperationResponse(operationRequest.OperationCode);
            
            //if (room.gameState == 0) // 0-未开始
            if (true) // 临时调试
            {
                Functions.AddPlayerFromRoomList(room, user); // 把自己放到房间里

                Dictionary<byte, object> data = new Dictionary<byte, object>();
                string roomString = Functions.ObjectToXmlString<Room>(room);
                data.Add((byte)ParameterCode.JoinRoom, roomString);
                response.Parameters = data;

                response.ReturnCode = (short)Common.ReturnCode.Success;
                peer.SendOperationResponse(response, sendParameters);

                //广播
                foreach (var ntfPeer in MyGameServer.Instance.peerList)
                {
                    if (string.IsNullOrEmpty(ntfPeer.username) == false)
                    {
                        bool isInRoom = Functions.IsPlayerInRoom(room, ntfPeer.uuid);
                        if (isInRoom)
                        {
                            EventData ed = new EventData((byte)EventCode.JoinRoom);
                            Dictionary<byte, object> dataEvent = new Dictionary<byte, object>();

                            //CommonUser player = new CommonUser();
                            //user.id = tempPeer.uuid;
                            //user.readyState = readyState;
                            string rommString2 = Functions.ObjectToXmlString<Room>(room);
                            dataEvent.Add((byte)ParameterCode.JoinRoom, rommString2);

                            ed.Parameters = dataEvent;
                            ntfPeer.SendEvent(ed, sendParameters);
                        }
                    }
                }
            }
            else
            {
                response.ReturnCode = (short)Common.ReturnCode.Failed;
                peer.SendOperationResponse(response, sendParameters);
            }
        }
    }
}
